import {
    stuDetailSubmit,
    colSchSubmit
} from 'common/src/api/studentinfo';

/**
 * 提交字段
 * @param {*学生Id} studentId
 * @param {*文件列表} fileList
 * @param {*修改描述} modifyDesc
 * @param {*发送对象的深拷贝} postData
 * @param {*获取的原对象,用来与发送对象对比差异} oldData
 * @param {*回调函数} cb
 */
export function submitField(
    studentId,
    fileList,
    modifyDesc,
    postData,
    oldData,
    cb
) {
    let params = {
        studentId: studentId,
        appliFields: [],
        evidence: fileList,
        modifyDescri: modifyDesc
    };
    // 处理审核字段
    postData.stuDetailInfoList.forEach(row => {
    // id为null为新增，id有值为修改或删除
        if (row.id) {
            // 某一行stuAttriInfos，可能返回多张表的column集合，有概率出现相同的column，所以用from和id来过滤
            let row__ = oldData.find(row_ => {
                let oldFrom = row_.stuAttriInfos[0].from;
                let newFrom = row.stuAttriInfos[0].from;
                if (oldFrom === newFrom && row.id === row_.id) {
                    return true;
                }
                return false;
            });
            row.stuAttriInfos
                .filter(c => c.isCollegeCheck || c.isSchoolCheck) // 仅提交审核字段
                .forEach(newColumn => {
                    let oldColumn = row__.stuAttriInfos.find(
                        c =>
                            c.column === newColumn.column &&
            c.from === newColumn.from
                    );
                    if (oldColumn) {
                        params.appliFields.push({
                            column: oldColumn.column,
                            oldColValue: oldColumn.columnValue,
                            newColValue: newColumn.columnValue,
                            from: oldColumn.from,
                            fieldId: oldColumn.fieldId,
                            id: row.id,
                            isCollegeCheck: oldColumn.isCollegeCheck,
                            isSchoolCheck: oldColumn.isSchoolCheck,
                            operType: row.operType,
                            newRealValue: newColumn.newRealValue,
                            oldRealValue: newColumn.oldRealValue
                        });
                    }
                });
        } else {
            row.stuAttriInfos
                .filter(c => c.isCollegeCheck || c.isSchoolCheck)
                .forEach(newColumn => {
                    params.appliFields.push({
                        column: newColumn.column,
                        oldColValue: null,
                        newColValue: newColumn.columnValue,
                        from: newColumn.from,
                        fieldId: newColumn.fieldId,
                        id: null,
                        isCollegeCheck: newColumn.isCollegeCheck,
                        isSchoolCheck: newColumn.isSchoolCheck,
                        newRealValue: newColumn.newRealValue,
                        oldRealValue: newColumn.oldRealValue
                    });
                });
        }
    });
    // 提交审核
    colSchSubmit(params).then(res => {
        if (res.code === 200) {
            submitNoCheck(postData, cb);
        }
    });
}

/**
 * 提交非审核字段
 * @param {*发送对象} postData
 * @param {*回调方法} cb
 */
function submitNoCheck(postData, cb) {
    // 过滤所有审核字段
    postData.stuDetailInfoList.forEach(row => {
        row.stuAttriInfos = row.stuAttriInfos.filter(
            field => field.isSchoolCheck === 0 && field.isCollegeCheck === 0
        );
    });
    postData.stuDetailInfoList = postData.stuDetailInfoList.filter(
        row => row.stuAttriInfos.length > 0
    );
    let containNoCheckField = postData.stuDetailInfoList.length !== 0;
    if (containNoCheckField) {
        stuDetailSubmit(postData).then(res => {
            if (res.code === 200) {
                cb();
            }
        });
    } else {
        cb();
    }
}

function validateFloat(rule, value, callback) {
    if (isNaN(value)) {
        callback(new Error('请输入有效数字'));
    } else {
        callback();
    }
}

function validateLong(rule, value, callback) {
    if (value && !/^\d+$/.test(value)) {
        callback(new Error('请输入有效整数'));
    } else {
        callback();
    }
}
/**
 * 获取表单规则
 *      针对证件类型和证件号码，特殊处理
 * @param {*} column 当前表单列
 * @param {*} relationMap 关系映射，证件号码与证件类型
 * @param {*} targetColumn 证件目标列
 * @param {*} dateRangeMap 日期映射
 * @param {*} dateColumn 日期列
 * @param {*} isEdit 是否为编辑状态
 */
export function getRules(
    column,
    relationMap,
    targetColumn,
    dateRangeMap,
    dateColumn,
    isEdit = true
) {
    let rules = [];
    requireRule(rules, column);
    if (isEdit && column.isEdit) {
        numberRules(rules, column);
        regularRules(rules, column, relationMap, targetColumn);
        dateRangeRules(rules, column, dateRangeMap, dateColumn);
    }
    return rules.length > 0 ? rules : null;
}
/**
 * 必填规则
 * @param {*} rules 规则集合
 * @param {*} column 列
 */
function requireRule(rules, column) {
    if (column.isRequire) {
        let actionType = '必须填写';
        if (column.type === 'select') {
            actionType = '必须选择';
            rules.push({
              required: true,
              message: actionType + column.nameZH,
              trigger: 'change'
            });
          } else {
            rules.push({
              required: true,
              message: actionType + column.nameZH,
              trigger: 'blur'
            });
          }
    }
}
/**
 * 数字规则
 * @param {*} rules  规则集合
 * @param {*} column 列
 */
function numberRules(rules, column) {
    if (column.dataType === 'float') {
        rules.push({
            validator: validateFloat,
            trigger: 'blur'
        });
    }
    if (column.dataType === 'long' && column.type !== 'date') {
        rules.push({
            validator: validateLong,
            trigger: 'blur'
        });
    }
    if (column.dataType === 'int' && column.type !== 'date') {
        rules.push({
            validator: validateLong,
            trigger: 'blur'
        });
    }
}
/**
 * 正则表达式规则
 * @param {s} rules 规则集合
 * @param {*} column 列
 * @param {*} relationMap 证件关系
 * @param {*} targetColumn 目标列
 */
function regularRules(rules, column, relationMap, targetColumn) {
    if (column.legalityCheck) {
        if (relationMap && relationMap.has(column.column)) {
            rules.push({
                trigger: 'blur',
                validator: (rule, value, callback) => {
                    if (!targetColumn || targetColumn.columnValue !== '01') {
                        callback();
                    } else {
                        let reg = new RegExp(column.legalityCheck);
                        if (value && !reg.test(value)) {
                            let msg = column.errorMessage || '输入的格式有误';
                            callback(new Error(msg));
                        } else {
                            callback();
                        }
                    }
                }
            });
        } else {
            rules.push({
                trigger: 'blur',
                validator: (rule, value, callback) => {
                    let reg = new RegExp(column.legalityCheck);
                    if (value && !reg.test(value)) {
                        let msg = column.errorMessage || '输入的格式有误';
                        callback(new Error(msg));
                    } else {
                        callback();
                    }
                }
            });
        }
    }
}
/**
 * 日期范围规则
 * @param {*} rules 规则集合
 * @param {*} currentColumn 当前列
 * @param {*} dateRangeMap 映射关系
 * @param {*} targetColumn 目标列
 */
function dateRangeRules(rules, currentColumn, dateRangeMap, targetColumn) {
    if (
        dateRangeMap &&
    dateRangeMap.has(currentColumn.column) &&
    targetColumn
    ) {
        rules.push({
            trigger: 'blur',
            validator: (rule, value, callback) => {
                if (currentColumn.columnValue && targetColumn.columnValue) {
                    let startDate = new Date(targetColumn.columnValue);
                    let endDate = new Date(currentColumn.columnValue);
                    if (startDate > endDate) {
                        callback(new Error('结束日期不能小于开始日期'));
                    } else {
                        callback();
                    }
                } else {
                    callback();
                }
            }
        });
    }
}

export function getCitys(options) {
    if (!options.hasOwnProperty('G_XZQY')) {
        return [];
    }
    return options.G_XZQY.filter(
        c => c.value.length === 6
    ).map(c => {
        let pid = null;
        if (c.value.substr(4) !== '00') {
            pid = c.value.substr(0, 4) + '00';
        } else if (
            c.value.substr(4) === '00' &&
      c.value.substr(2, 2) !== '00'
        ) {
            pid = c.value.substr(0, 2) + '0000';
        } else {
            pid = 0;
        }
        return {
            id: c.value,
            label: c.label.replace(/(^\s*)|(\s*$)/g, ''),
            pid: pid
        };
    });
}
export function getCityNameByValue(value, citys, splitChar = '') {
    let node = citys.find(c => c.id == value);
    if (node) {
        if (node.pid == 0) {
            return node.label;
        } else {
            let parentNode = citys.find(c => c.id == node.pid);
            if (parentNode == null) {
                return node.label;
            }
            if (parentNode.pid == 0) {
                return parentNode.label + splitChar + node.label;
            } else {
                let grandfatherNode = citys.find(c => c.id == parentNode.pid);
                if (grandfatherNode) {
                    return grandfatherNode.label + splitChar + parentNode.label + splitChar + node.label;
                } else {
                    return parentNode.label + splitChar + node.label;
                }
            }
        }
    } else {
        return value;
    }
    // return null;
}
